/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.swan.plugin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.swan.plugin.bean.CustomerDesignBean;
import org.swan.plugin.bean.Pojo;
import org.swan.plugin.util.Template;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * Goal which touches a timestamp file.
 */
@Mojo(name = "pojo", defaultPhase = LifecyclePhase.NONE)
public class PojoMojo extends AbstractMojo {
    /**
     * Location of the file.
     */
    @Parameter(defaultValue = "${project.build.directory}/generated-sources/robot", property = "pojo.outputPath", required = true)
    private File outputDirectory;
    @Parameter(defaultValue = "${project.basedir}/template", property = "pojo.dataPath", required = true)
    private File basedir;
    @Parameter(defaultValue = "${project.basedir}", property = "pojo.templatePath", required = true)
    private File templatePath;
    private static final String DEFAULT_TEMPLATE = "inner/template/pojo.btl";

    public void execute() throws MojoExecutionException, MojoFailureException {
        File privateFolder = basedir;
        if (!privateFolder.exists())
            privateFolder.mkdirs();
        getLog().info("Start to run robot:" + privateFolder.getAbsolutePath());
        list(privateFolder, f -> f.getName().endsWith(".pojo.json"), f -> {
            try {
                getLog().info(f.getName());
                ObjectMapper om = new ObjectMapper();
                CollectionType collectionType = om.getTypeFactory().constructCollectionType(List.class, Pojo.class);
                List<Pojo> o = om.readValue(f, collectionType);
                for (Pojo pojo : o) {
                    if (pojo.getTemplate() == null)
                        continue;
                    for (Pojo.TemplateBean templateBean : pojo.getTemplate()) {
                        generateFile(pojo, templateBean);
                    }
                }
            } catch (IOException e) {
                getLog().error(e);
            }
        });
        list(privateFolder, f -> f.getName().endsWith(".def.json"), f -> {
            try {
                getLog().info(f.getName());
                ObjectMapper om = new ObjectMapper();
                CustomerDesignBean<?> o = om.readValue(f, CustomerDesignBean.class);
                if (o.getTemplate() == null)
                    return;
                for (Pojo.TemplateBean templateBean : o.getTemplate()) {
                    generateFile(o, templateBean);
                }

            } catch (IOException e) {
                getLog().error(e);
            }
        });
    }

    private void generateFile(CustomerDesignBean<?> pojo, Pojo.TemplateBean templateBean) throws IOException {
        String templateResource = DEFAULT_TEMPLATE;
        if (templateBean.getUrl() != null)
            templateResource = templateBean.getUrl();
        if (templateResource.startsWith(Pojo.TemplateBean.CLASSPATH_PREFIX)) {
            templateResource = templateResource.substring(Pojo.TemplateBean.CLASSPATH_PREFIX.length());
        }
        Template template = new Template().setResource(templateResource);
        File targetFile = new File(outputDirectory, templateBean.getTargetUrl());
        getLog().info("==> " + targetFile.getAbsolutePath());
        if (!targetFile.getParentFile().exists())
            targetFile.getParentFile().mkdirs();
        template.putVariable("data", pojo.getData());
        template.putVariable("className", templateBean.getClassName());
        template.putVariable("packageName", templateBean.getPackageName());
        template.putVariable("description", templateBean.getDescription());
        template.putVariable("templateUrl", templateBean.getUrl());
        if (templateBean.getUrl() == null || DEFAULT_TEMPLATE.equals(templateBean.getUrl()) || templateBean.getUrl().startsWith(Pojo.TemplateBean.CLASSPATH_PREFIX)) {
            template.generateResourceTemplateTo(targetFile);
        } else {
            template.generateFileTemplateTo(targetFile);
        }
    }

    private void generateFile(Pojo pojo, Pojo.TemplateBean templateBean) throws IOException {
        Template template = new Template().setResource(templateBean.getUrl() == null ? DEFAULT_TEMPLATE : (templatePath + Template.SEPARATE + templateBean.getUrl()));
        File targetFile = new File(outputDirectory, templateBean.getTargetUrl());
        getLog().info("==> " + targetFile.getAbsolutePath());
        if (!targetFile.getParentFile().exists())
            targetFile.getParentFile().mkdirs();
        pojo.addExtraField("className", templateBean.getClassName());
        pojo.addExtraField("packageName", templateBean.getPackageName());
        pojo.addExtraField("description", templateBean.getDescription());
        pojo.addExtraField("templateUrl", templateBean.getUrl());
        template.putVariable("pojo", pojo);
        if (templateBean.getUrl() == null || DEFAULT_TEMPLATE.equals(templateBean.getUrl())) {
            template.generateResourceTemplateTo(targetFile);
        } else {
            template.generateFileTemplateTo(targetFile);
        }
    }

    private void list(File file, Predicate<File> predicate, Consumer<File> consumer) {
        for (File f : file.listFiles()) {
            if (f.isDirectory()) {
                list(f, predicate, consumer);
            } else {
                if (predicate.test(f))
                    consumer.accept(f);
            }
        }
    }

}
